package com.ruoyi.web.controller.recruit;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.recruit.domain.RecruitFile;
import com.ruoyi.recruit.domain.RecruitResult;
import com.ruoyi.recruit.domain.Recruiter;
import com.ruoyi.recruit.domain.vo.RecruiterVo;
import com.ruoyi.recruit.service.IRecruiterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author MMDZ
 * @date 2022/10/24 13:32
 * @description TODO 招聘
 */
@RestController
@RequestMapping("/recruit/recruiter")
public class RecruiterController extends BaseController {

    @Autowired
    private IRecruiterService recruiterService;

    @PreAuthorize("@ss.hasPermi('recruit:recruiter:list')")
    @GetMapping("/list")
    public TableDataInfo list(Recruiter recruiter) {
        startPage();
        List<RecruiterVo> list = recruiterService.selectList(recruiter);
        return getDataTable(list);
    }

    /**
     * 导出
     */
    @PreAuthorize("@ss.hasPermi('recruit:recruiter:export')")
    @Log(title = "导出人才库数据信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Recruiter recruiter) {
        List<RecruiterVo> list = recruiterService.selectList(recruiter);
        ExcelUtil<RecruiterVo> util = new ExcelUtil<RecruiterVo>(RecruiterVo.class);
        util.exportExcel(response, list, "人才库数据信息");
    }

    /**
     * 详细信息
     */
    @PreAuthorize("@ss.hasPermi('recruit:recruiter:query')")
    @GetMapping(value = "/{recruitId}")
    public AjaxResult getInfo(@PathVariable("recruitId") Long recruitId) {
        return AjaxResult.success(recruiterService.selectById(recruitId));
    }

    @PreAuthorize("@ss.hasPermi('recruit:recruiter:query')")
    @GetMapping(value = "/result/{recruitResultId}")
    public AjaxResult getResultInfo(@PathVariable("recruitResultId") Long recruitResultId) {
        return AjaxResult.success(recruiterService.selectResultById(recruitResultId));
    }

    /**
     * 新增
     */
    @PreAuthorize("@ss.hasPermi('recruit:recruiter:add')")
    @Log(title = "新增招聘人员信息", businessType = BusinessType.INSERT)
    @PostMapping()
    public AjaxResult add(@Validated @RequestBody Recruiter recruiter) {
        recruiter.setCreateBy(getUsername());
        return toAjax(recruiterService.insertRecruiter(recruiter));
    }

    @PreAuthorize("@ss.hasPermi('recruit:recruiter:add')")
    @Log(title = "新增招聘人员面试信息", businessType = BusinessType.INSERT)
    @PostMapping(value = "/result")
    public AjaxResult addResult(@Validated @RequestBody RecruitResult recruitResult) {
        recruitResult.setCreateBy(getUsername());
        return toAjax(recruiterService.insertRecruitResult(recruitResult));
    }

    /**
     * 修改
     */
    @PreAuthorize("@ss.hasPermi('recruit:recruiter:edit')")
    @Log(title = "修改招聘人员信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody Recruiter recruiter) {
        recruiter.setUpdateBy(getUsername());
        return toAjax(recruiterService.updateRecruiter(recruiter));
    }

    @PreAuthorize("@ss.hasPermi('recruit:recruiter:edit')")
    @Log(title = "修改招聘人员面试信息", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/result")
    public AjaxResult editResult(@Validated @RequestBody RecruitResult recruitResult) {
        recruitResult.setUpdateBy(getUsername());
        return toAjax(recruiterService.updateRecruitResult(recruitResult));
    }

    /**
     * 文件列表
     */
    @GetMapping("/files/{recruitId}")
    public AjaxResult fileList(@PathVariable("recruitId") Long recruitId) {
        List<RecruitFile> list = recruiterService.selectFileList(recruitId);
        return AjaxResult.success(list);
    }

    /**
     * 上传人才信息
     *
     * @param file
     * @return
     */
    @PreAuthorize("@ss.hasPermi('recruit:recruiter:upload')")
    @Log(title = "上传人才信息", businessType = BusinessType.UPLOAD)
    @PostMapping("/upload/{recruitId}")
    public AjaxResult fileUpload(MultipartFile file, @PathVariable("recruitId") Long recruitId) throws IOException {
        return recruiterService.fileUpload(file, recruitId);
    }

    /**
     * 下载 人才信息
     *
     * @param resource
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/download/resource")
    public void fileDownload(String resource, HttpServletRequest request, HttpServletResponse response) {
        try {
            if (!FileUtils.checkAllowDownload(resource)) {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = RuoYiConfig.getRecruitPath();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
            logger.error("下载文件失败", e);
        }
    }

    /**
     * 预览文件 (获取文件全路径)
     */
    @PreAuthorize("@ss.hasPermi('recruit:recruiter:view')")
    @GetMapping("/view")
    public AjaxResult viewFile(String resource) {
        // 本地资源根路径
        String localPath = RuoYiConfig.getRecruitPath();
        // 本地资源路径访问路径
        String localFullPath = "file:" + localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
        return AjaxResult.success("操作成功", localFullPath);
    }

    /**
     * 删除文件
     */
    @PreAuthorize("@ss.hasPermi('recruit:recruiter:remove')")
    @Log(title = "删除人才文件", businessType = BusinessType.DELETE)
    @DeleteMapping("/{recruitFileId}")
    public AjaxResult delFile(@PathVariable Long recruitFileId) {
        return toAjax(recruiterService.deleteRecruitFile(recruitFileId));
    }
}
